package org.cs456.data;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.location.Location;
import android.media.ExifInterface;
import android.net.Uri;
import android.text.format.Time;
import android.util.Log;

public class Image {
	public ExifInterface EXIF;
	private File file;
	private Context context;
	Db db;

	public Image(Context ctxt, String path) {
		
		file = new File(path);
		try {
			EXIF = new ExifInterface(getFilePath());
			context = ctxt;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getFilePath(){
		return file.getAbsolutePath();
	}
	
	public String getName(){
		return getFilePath();
	}

	public Uri getURI() {
		return Uri.fromFile(file);
	}

	public int getHeight() {
		return EXIF.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 1);
	}
	
	public int getWidth() {
		return EXIF.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 1);
	}

	public void setLocation(Location loc){
		if(loc != null){
		EXIF.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, String.valueOf(loc.getTime()));
		EXIF.setAttribute(ExifInterface.TAG_GPS_LATITUDE, String.valueOf(loc.getLatitude()));
		EXIF.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, String.valueOf(loc.getLongitude()));
		EXIF.setAttribute("GPSAltitude", String.valueOf(loc.getAltitude()));
		}

	}
	
	public void setOrientation(int orientation) {
		EXIF.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation));
	}

	
	public void setTimestamp(Time time){
		if(time != null){
			EXIF.setAttribute(ExifInterface.TAG_DATETIME, time.format3339(false));
		}

	}
	
	public void setMake(String make){
		if(make != null){
			EXIF.setAttribute(ExifInterface.TAG_MAKE, make);
		}

	}
	public void setModel(String model){
		if(model != null){
			EXIF.setAttribute(ExifInterface.TAG_MODEL, model);
		}

	}


	public void saveToDatabase() {
		db = new Db(context);
		try {
			db.open();
			db.insert(this);
		} catch (Exception ex) {

		}finally{
			db.close();
		}
	}

	static public Image find(Context ctxt, int imgNum) {
		Db db = new Db(ctxt);
		Cursor c = null;
		try {
			db.open();
			c = db.findImage(imgNum);
			c.moveToFirst();
			String path = c.getString(c.getColumnIndex("path"));
			return new Image(ctxt, path);
		} catch (CursorIndexOutOfBoundsException ex) {
			Log.d("CS456 " , imgNum + ex.getMessage());
			return null;
		} finally {
			if (c != null)
				c.close();
			db.close();
		}
	}
	
	static public long count(Context ctxt) {
		Db db = new Db(ctxt);
		long count = 0;
		try {
			db.open();
			count = db.count(DbConstants.IMAGE_TABLE);
			db.close();
		} catch (Exception ex) {

		}
		Log.v("Image Count:", "" + count);
		return count;
	}


}
